﻿using QDasConverter.Core;
using QDasConverter.Utils;
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using WindGoes6.Controls;

namespace QDasConverter.Forms
{
    public partial class ConfigForm : Form
    {
        public ConfigurationData pd = new ConfigurationData();
        public bool needSave = false;
        IniAccess ia = new IniAccess();

        public ConfigForm()
        {
            InitializeComponent();
        }

        private void setFolder(TextBox tb)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.SelectedPath = tb.Text;
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tb.Text = fbd.SelectedPath;
            }
        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {
            Text += $" (当前配置文件: {IniAccess.DefaultConfigFile})";

            //pgInput 
            rbBackup.Checked = pd.ProcessSourceFileType == 0;
            rbKeepInputFileLocation.Checked = pd.ProcessSourceFileType == 1;
            rbDelete.Checked = pd.ProcessSourceFileType == 2;
            gbBackupFolders.Enabled = rbBackup.Checked;
            txtSuccessfulFolder.Text = pd.IO_FolderForSuccessed;
            txtFailedFolder.Text = pd.IO_FolderForFailed;
            ckKeepBackupFolderStruct.Checked = pd.KeepBackupFolderStructType == 1;

            // pgOutput
            txtOutputFolder.Text = pd.IO_OutputFolder;
            txtTempFolder.Text = pd.IO_TempFolder;
            if (pd.DealSameOutputFileNameType == 0)
                rbReplaceOld.Checked = true;
            else if (pd.DealSameOutputFileNameType == 1)
                rbAddTimeToNew.Checked = true;
            else if (pd.DealSameOutputFileNameType == 2)
                rbIncrementIndex.Checked = true;
            else if (pd.DealSameOutputFileNameType == 3)
                rbMergeOutputFiles.Checked = true;

            ckKeepOutFolderStruct.Checked = pd.KeepOutFolderStructLevel >= 0;
            numlblKeepFolderLevel.Enabled = ckKeepOutFolderStruct.Checked;
            int lv = (int)Math.Abs(pd.KeepOutFolderStructLevel);
            numlblKeepFolderLevel.Value = lv < 1 ? 1 : lv;

            if (string.IsNullOrEmpty(pd.CostomizedDateTimeFormat))
            {
                rbNoDatetimeAppendix.Checked = true;
            }
            else if (pd.CostomizedDateTimeFormat == "#default#")
            {
                rbUseDefaultDateTimeAppendix.Checked = true;
            }
            else
            {
                rbUseCustomizedDateAppendix.Checked = true;
                txtCustomedDateFormat.Text = pd.CostomizedDateTimeFormat;
            }



            //pgAutoTransducer
            cbCircleUnit.SelectedIndex = 1;
            if (pd.SupportAutoTransducer)
            {
                ckAutoTransduce.Checked = pd.AutoTransducerAvaliable;
                gbAutoConfig.Enabled = pd.AutoTransducerAvaliable;
                numCircleValue.Value = pd.CircleValue;
                cbCircleUnit.SelectedIndex = pd.CircleUnit;
                dpStartTime.Value = pd.StartTime;
                dpEndTime.Value = pd.EndTime;
            }

            if (!pd.SupportAutoTransducer)
            {
                tabControl1.TabPages.Remove(pgAutoTransducer);
            }

            ckTraverseSubfolders.Checked = pd.TraverseSubfolders;

            /***** encoding page *****/
            lbInputEncoding.Items.Clear(); 
            lbOutputEncoding.Items.Clear();
            foreach (var item in Config.AllEncodings)
            {
                lbInputEncoding.Items.Add(item);
                lbOutputEncoding.Items.Add(item);
            }

            // lbInputEncoding.SelectedIndex = pd.EncodingID;
            //foreach (Encoding ed in ConfigurationData.Encodings)
            //{
            //    lbInputEncoding.Items.Add(ed.BodyName.ToUpper());
            //    lbOutputEncoding.Items.Add(ed.BodyName.ToUpper());
            //}

            ckConfirmClose.Checked = pd.UI_AskBeforeClosing;

            // ControlHelper.AddBoollonTip(btnDateFormatInformation, "日期格式说明", values.DateFormatIntroduction);
            tabControl1.TabPages.RemoveAt(3);
            tabControl1.TabPages.RemoveAt(1);

            // 初始化两个Encoding列表

            // 2021/11/13 加入内容，直接加载本项目所需要的数据
            txtLastResID.Text = ia.ReadString(Config.LastResID, "0");
            numBatchCount.Value = ia.ReadInt(Config.BatchCount, 50);
            numConvertInterval.Value = ia.ReadInt(Config.ConvertInterval, 60);
            lbInputEncoding.SelectedIndex = ia.ReadInt(Config.InputEncodingIndex, 0);
            lbOutputEncoding.SelectedIndex = ia.ReadInt(Config.OutputEncodingIndex, 0);

            foreach (var item in Enum.GetValues(typeof(TsingShanConverters)))
                cbAllConverters.Items.Add(item);
            cbAllConverters.Text = ia.ReadString(Config.Converter, TsingShanConverters.C2021T02_cvinet.ToString());
            if (cbAllConverters.Items.Count > 0 && cbAllConverters.SelectedIndex < 0)
                cbAllConverters.SelectedIndex = 0;
        }

        private void btOutputFolder_Click(object sender, EventArgs e)
        {
            setFolder(txtOutputFolder);
        }

        private void btnTempFolder_Click(object sender, EventArgs e)
        {
            setFolder(txtTempFolder);
        }

        private void btnSuccessfulFolder_Click(object sender, EventArgs e)
        {
            setFolder(txtSuccessfulFolder);
        }

        private void btnFailedFolder_Click(object sender, EventArgs e)
        {
            setFolder(txtFailedFolder);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            needSave = true;

            /***************************************************/
            // 2021-10-02 加入，只用于ini的保存
            ia.WriteValue(Config.OutputDirectory, txtOutputFolder.Text);
            ia.WriteValue(Config.TempDirectory, txtTempFolder.Text);
            // 2021/11/13 加入内容，直接加载本项目所需要的数据
            ia.WriteValue(Config.LastResID, txtLastResID.Text);
            ia.WriteValue(Config.BatchCount, numBatchCount.Value.ToString());
            ia.WriteValue(Config.ConvertInterval, numConvertInterval.Value.ToString());
            ia.WriteValue(Config.InputEncodingIndex, lbInputEncoding.SelectedIndex.ToString());
            ia.WriteValue(Config.OutputEncodingIndex, lbOutputEncoding.SelectedIndex.ToString());
            ia.WriteValue(Config.Converter, cbAllConverters.Text);
            /***************************************************/

            // pgOutput
            pd.IO_OutputFolder = txtOutputFolder.Text;
            pd.IO_TempFolder = txtTempFolder.Text;
            if (rbReplaceOld.Checked)
                pd.DealSameOutputFileNameType = 0;
            else if (rbAddTimeToNew.Checked)
                pd.DealSameOutputFileNameType = 1;
            else if(rbIncrementIndex.Checked)
                pd.DealSameOutputFileNameType = 2;
            else if (rbMergeOutputFiles.Checked)
                pd.DealSameOutputFileNameType = 3;

            pd.KeepOutFolderStructLevel = ckKeepOutFolderStruct.Checked ? (int)numlblKeepFolderLevel.Value : -1;
            pd.KeepBackupFolderStructLevel = ckKeepOutFolderStruct.Checked ? (int)numlblKeepFolderLevel.Value : 0;
            pd.CostomizedDateTimeFormat = rbNoDatetimeAppendix.Checked ? "" : rbUseDefaultDateTimeAppendix.Checked ? "#default#" : txtCustomedDateFormat.Text;

            //pgBackups
            if (rbBackup.Checked)
                pd.ProcessSourceFileType = 0;
            else if (rbKeepInputFileLocation.Checked)
                pd.ProcessSourceFileType = 1;
            else if (rbDelete.Checked)
                pd.ProcessSourceFileType = 2;

            pd.KeepBackupFolderStructType = ckKeepBackupFolderStruct.Checked ? 1 : 0;
            pd.IO_FolderForSuccessed = txtSuccessfulFolder.Text;
            pd.IO_FolderForFailed = txtFailedFolder.Text;

            //pgAutoTransducer
            pd.AutoTransducerAvaliable = ckAutoTransduce.Checked;
            if (pd.AutoTransducerAvaliable)
            {
                pd.CircleValue = (int)numCircleValue.Value;
                pd.CircleUnit = cbCircleUnit.SelectedIndex;
                pd.StartTime = dpStartTime.Value;
                pd.EndTime = dpEndTime.Value;
            }

            pd.TraverseSubfolders = ckTraverseSubfolders.Checked;

            /****** Encoding page ******/
            pd.EncodingID = lbInputEncoding.SelectedIndex;

            // Common.transducer.SaveConfig();

            pd.UI_AskBeforeClosing = ckConfirmClose.Checked;

            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ckKeepFolderStruct_Click(object sender, EventArgs e)
        {
            numlblKeepFolderLevel.Enabled = ckKeepOutFolderStruct.Checked;
        }

        private void ckAutoTransfer_Click(object sender, EventArgs e)
        {
            gbAutoConfig.Enabled = ckAutoTransduce.Checked;
        }

        private void rbBackup_CheckedChanged(object sender, EventArgs e)
        {
            gbBackupFolders.Enabled = true;
        }

        private void rbNoChange_CheckedChanged(object sender, EventArgs e)
        {
            gbBackupFolders.Enabled = false;
        }

        private void rbDelete_CheckedChanged(object sender, EventArgs e)
        {
            gbBackupFolders.Enabled = false;
        }

        private void CkKeepOutFolderStruct_CheckedChanged(object sender, EventArgs e)
        {
            numlblKeepFolderLevel.Enabled = ckKeepOutFolderStruct.Checked;
        }

        private void NumlblKeepFolderLevel_ValueChanged(object sender, EventArgs e)
        {

        }

        private void BtnDateFormatInformation_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("**** 格式说明 ****");
            sb.AppendLine("[1001]: 4位数字，表示从DFQ文件中零件层的值，如 1001 对应K1001的值，注意要带中括号但不要带K。");
            sb.AppendLine("yyyy: 4位年份");
            sb.AppendLine("MM: 2位月份");
            sb.AppendLine("dd: 2位日");
            sb.AppendLine("HH 24 小时制的小时。");
            sb.AppendLine("mm 分钟。一位数的分钟数有一个前导零。 ");
            sb.AppendLine("ss 秒。一位数的秒数有一个前导零。 ");
            sb.AppendLine("fff: 三位毫秒。其余数字被截断。 ");
            sb.AppendLine("");
            sb.AppendLine("**** 示例 ****");
            sb.AppendLine("假定输入文件名为 tx10.dfq，其K1001的值为 XV3256C ");
            sb.AppendLine("_yyyyMMdd 输出 tx10_20201102.dfq");
            sb.AppendLine("_yyyyMMdd_HHmmss 输出 tx10_20201102_103233.dfq");
            sb.AppendLine("_[1001]_yyyyMMdd_HHmmss 输出 tx10_XV3256C_20201102_103233.dfq");
            MessageBox.Show(sb.ToString(), "格式说明", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void TxtCustomedDateFormat_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string dtfmt = DateTime.Now.ToString(txtCustomedDateFormat.Text);
                txtCustomedDateFormatResult.Text = $"output.dfq -> output_{dtfmt}.dfq";
            }
            catch
            {
                txtCustomedDateFormatResult.Text = $"格式有误";
            }
        }



        private void RbUseDefaultDateTimeFormat_CheckedChanged(object sender, EventArgs e)
        {
            UpdateDateTimeFormatGroupBox();
        }


        private void RbUseCustomizedDateFormat_CheckedChanged(object sender, EventArgs e)
        {
            UpdateDateTimeFormatGroupBox();
        }

        private void RbNoDatetimeAppendix_CheckedChanged(object sender, EventArgs e)
        {
            UpdateDateTimeFormatGroupBox();
        }

        private void UpdateDateTimeFormatGroupBox()
        {
            groupBox6.Enabled = rbUseCustomizedDateAppendix.Checked;
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void cbAllConverters_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
